"use strict";

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var app = angular.module("myApp", []);

app.controller("mainController", ['$scope', '$compile', '$sce', function ($scope, $compile) {
    $scope.toJSON = function (val) {
        return angular.toJson(val, true);
    };

    $scope.faults = FaultNode.faults;
    FaultNode.loadFaults.callbacks.push(function () {
        return $scope.faults = FaultNode.faults;
    });

    $scope.components = ComponentNode.components;
    ComponentNode.loadComponents.callbacks.push(function () {
        return $scope.components = ComponentNode.components;
    });

    $scope.match_functions = MatchFunctionNode.functions;
    MatchFunctionNode.loadFunctions.callbacks.push(function () {
        return $scope.match_functions = MatchFunctionNode.functions;
    });
}]);

app.controller("faultQueryController2", ['$scope', '$rootScope', '$interval', '$timeout', '$uibModal', '$http', function ($scope, $rootScope, $interval, $timeout, $uibModal, $http) {
    $scope.signals = [];

    $scope.attachFacts = [];

    $scope.features = FeatureNode.features;
    $scope.featureTypes = FeatureNode.featureTypes;
    // FeatureNode.loadFeatures.callbacks.push(()=>{
    //     $scope.features=FeatureNode.features;
    //     $scope.featureTypes = FeatureNode.featureTypes;
    //     $scope.$apply();
    // });

    $interval(function () {
        // $http.get('http://localhost:8080/rest/signal/list', {
        //     headers: {
        //         'Accept': 'application/json',
        //         'Content-Type': 'application/json',
        //     }}).then(function (response) {
        //     console.info(response);
        //     $scope.signals = response.data;
        //     $scope.doMatch();
        // },function (response) {
        //     console.info(response);
        // });
        $.get('http://localhost:8080/rest/signal/list2', function (data) {
            $scope.signals = data;
            $scope.doMatch();
            $scope.$apply();
        });
    }, 6000);

    $scope.findComponent = function (id) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
            for (var _iterator = ComponentNode.components[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var cp = _step.value;

                if (cp.id == id) return cp;
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion && _iterator.return) {
                    _iterator.return();
                }
            } finally {
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }

        return { name: '未找到' };
    };

    $scope.doMatch = function () {
        FeatureNode.loadFeatures2("match (n:Feature)-[*]->(m:Component) where id(m) in $cids return n", { "cids": $scope.signals.map(function (signal) {
                return signal.component.id;
            }) }, function (features, featureTypes) {
            $scope.features = features;
            $scope.featureTypes = featureTypes;

            var _iteratorNormalCompletion2 = true;
            var _didIteratorError2 = false;
            var _iteratorError2 = undefined;

            try {
                for (var _iterator2 = $scope.features.filter(function (f) {
                    return f.isAuto();
                })[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                    var feature = _step2.value;

                    feature.isMatched = false;
                    var _iteratorNormalCompletion4 = true;
                    var _didIteratorError4 = false;
                    var _iteratorError4 = undefined;

                    try {
                        for (var _iterator4 = $scope.signals[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                            var signal = _step4.value;

                            //TODO 此处应判断元件是否匹配(元件组合AND OR)
                            var component_matched = false;
                            var _iteratorNormalCompletion5 = true;
                            var _didIteratorError5 = false;
                            var _iteratorError5 = undefined;

                            try {
                                for (var _iterator5 = feature.components[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
                                    var cpIds = _step5.value;

                                    if (signal.component.id == cpIds) {
                                        component_matched = true;
                                        break;
                                    }
                                }
                            } catch (err) {
                                _didIteratorError5 = true;
                                _iteratorError5 = err;
                            } finally {
                                try {
                                    if (!_iteratorNormalCompletion5 && _iterator5.return) {
                                        _iterator5.return();
                                    }
                                } finally {
                                    if (_didIteratorError5) {
                                        throw _iteratorError5;
                                    }
                                }
                            }

                            if (!component_matched) {
                                continue;
                            }

                            //此处判断特征值是否符合
                            if (feature.name == signal.featureType) {
                                feature.isMatched = matchFactory(feature.opertion)(signal.value, feature.params);
                                console.info(feature.opertion + " " + signal.value + " " + feature.params + " " + feature.isMatched);
                            }
                        }
                    } catch (err) {
                        _didIteratorError4 = true;
                        _iteratorError4 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion4 && _iterator4.return) {
                                _iterator4.return();
                            }
                        } finally {
                            if (_didIteratorError4) {
                                throw _iteratorError4;
                            }
                        }
                    }
                }
            } catch (err) {
                _didIteratorError2 = true;
                _iteratorError2 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion2 && _iterator2.return) {
                        _iterator2.return();
                    }
                } finally {
                    if (_didIteratorError2) {
                        throw _iteratorError2;
                    }
                }
            }

            $scope.faults = [];
            $scope.features //.filter(feature=>feature.isMatched)
            .forEach(function (feature, index) {
                if (!feature.isMatched) return;
                var session2 = neo4jService.getSession();
                var resultPromise2 = session2.run("start f=node(" + feature.id + ") MATCH (a:Fault)-[*]->(f) RETURN a");
                resultPromise2.then(function (result) {
                    session2.close();
                    // console.info(result);
                    result.records.map(function (record) {
                        return record.get(0);
                    }).map(function (node) {
                        return MyNode.fromNeo4jNode(node);
                    }).forEach(function (fault) {
                        fault.$state = 'partial';

                        $scope.features[index].$formFaults = fault.id;

                        var f_contains = false;
                        var _iteratorNormalCompletion3 = true;
                        var _didIteratorError3 = false;
                        var _iteratorError3 = undefined;

                        try {
                            for (var _iterator3 = $scope.faults[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                                var ff = _step3.value;

                                if (ff.id == fault.id) {
                                    f_contains = true;
                                    break;
                                }
                            }
                        } catch (err) {
                            _didIteratorError3 = true;
                            _iteratorError3 = err;
                        } finally {
                            try {
                                if (!_iteratorNormalCompletion3 && _iterator3.return) {
                                    _iterator3.return();
                                }
                            } finally {
                                if (_didIteratorError3) {
                                    throw _iteratorError3;
                                }
                            }
                        }

                        if (!f_contains) {
                            $scope.faults.push(fault);

                            var session4 = neo4jService.getSession();
                            var resultPromise4 = session4.run("start f=node(" + fault.id + ") MATCH (f)-[:hasFeatures]->(a) RETURN a");
                            resultPromise4.then(function (result) {
                                session4.close();

                                var nd = result.records[0].get(0);
                                $scope.matchFeature(nd, function () {
                                    fault.state = 'all';
                                    $scope.$apply();
                                });
                            });
                        }
                    });
                });
            });
        });
    };

    $scope.matchFeature = function (f, func) {
        if (f["labels"][0] == 'Feature') {
            //TODO 在此处补充对元件组的判断
            var _iteratorNormalCompletion6 = true;
            var _didIteratorError6 = false;
            var _iteratorError6 = undefined;

            try {
                for (var _iterator6 = $scope.features[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
                    var ff = _step6.value;

                    if (ff.id == f["identity"].toString()) {
                        if (ff.isMatched) {
                            func();
                        }
                    }
                }
            } catch (err) {
                _didIteratorError6 = true;
                _iteratorError6 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion6 && _iterator6.return) {
                        _iterator6.return();
                    }
                } finally {
                    if (_didIteratorError6) {
                        throw _iteratorError6;
                    }
                }
            }
        } else {
            var type = f.properties['type'];
            var session = neo4jService.getSession();
            var resultPromise = session.run("start f=node(" + f["identity"].toString() + ") MATCH (f)-[:contains]->(a) RETURN a");
            resultPromise.then(function (result) {
                session.close();

                var nds = result.records.map(function (record) {
                    return record.get(0);
                });

                if (type == 'or') {
                    var _iteratorNormalCompletion7 = true;
                    var _didIteratorError7 = false;
                    var _iteratorError7 = undefined;

                    try {
                        for (var _iterator7 = nds[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
                            var nd = _step7.value;

                            $scope.matchFeature(nd, func);
                        }
                    } catch (err) {
                        _didIteratorError7 = true;
                        _iteratorError7 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion7 && _iterator7.return) {
                                _iterator7.return();
                            }
                        } finally {
                            if (_didIteratorError7) {
                                throw _iteratorError7;
                            }
                        }
                    }
                } else {
                    (function () {
                        var ct = 0;
                        var _iteratorNormalCompletion8 = true;
                        var _didIteratorError8 = false;
                        var _iteratorError8 = undefined;

                        try {
                            for (var _iterator8 = nds[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
                                var _nd = _step8.value;

                                $scope.matchFeature(_nd, function () {
                                    ct++;
                                    if (ct == nds.length) {
                                        func();
                                    }
                                });
                            }
                        } catch (err) {
                            _didIteratorError8 = true;
                            _iteratorError8 = err;
                        } finally {
                            try {
                                if (!_iteratorNormalCompletion8 && _iterator8.return) {
                                    _iterator8.return();
                                }
                            } finally {
                                if (_didIteratorError8) {
                                    throw _iteratorError8;
                                }
                            }
                        }
                    })();
                }
            });
        }
    };

    $scope.showFaultTree = function (faultId) {
        // let query = `start n=node(${faultId}) match (n)-[*]->(p) return n,p`;
        // window.open(`http://127.0.0.1:8080/browser/NeoEmbed.html?query=${encodeURIComponent(query).replace(/=/g,'%3d')}`);
        // $rootScope.$broadcast('graph_fault_show', { message: faultId });
        // $('#myTabs li:eq(1) a').tab('show');

    };

    $scope.showFaultReport = function (faultId) {
        var fault = null;
        var _iteratorNormalCompletion9 = true;
        var _didIteratorError9 = false;
        var _iteratorError9 = undefined;

        try {
            for (var _iterator9 = $scope.faults[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
                var f = _step9.value;

                if (f.id == faultId) {
                    fault = f;
                    break;
                }
            }
        } catch (err) {
            _didIteratorError9 = true;
            _iteratorError9 = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion9 && _iterator9.return) {
                    _iterator9.return();
                }
            } finally {
                if (_didIteratorError9) {
                    throw _iteratorError9;
                }
            }
        }

        var features = [];
        $scope.features.forEach(function (f) {
            if (f.$formFaults == faultId) {
                features.push(f);
            }
        });
        $scope.modelData = {
            fault: fault,
            features: features
        }; //用于传递数据

        var modalInstance = $uibModal.open({
            templateUrl: 'template/report.html', //script标签中定义的id
            controller: 'ReportController', //modal对应的Controller
            scope: $scope
        });
    };

    $scope.showNowReport = function () {
        $scope.modelData = {
            fault: null,
            features: []
        }; //用于传递数据

        var modalInstance = $uibModal.open({
            templateUrl: 'template/report.html', //script标签中定义的id
            controller: 'ReportController', //modal对应的Controller
            scope: $scope
        });
    };

    $scope.matchFaultTree = function (faultId) {
        $scope.matchingFaultId = faultId;
    };

    $scope.matchingFaultId = 0;
}]);

app.controller('ReportController', ['$scope', '$uibModalInstance', '$window', function ($scope, $uibModalInstance, $window) {
    $scope.fault = $scope.modelData.fault;
    $scope.features = $scope.modelData.features;

    console.info($scope.modelData);

    $scope.sequence = '001232016072010010121001';

    $scope.reasons = [];

    if ($scope.fault != null) {
        Graph.loadGraph($scope.fault.id, function (g) {
            $scope.graph = g;
            var nodesList = [].concat(_toConsumableArray(g.nodes.values()));
            $scope.reasons = nodesList.filter(function (node) {
                return node.$type == 'Reason';
            }).sort(function (a, b) {
                return a > b;
            });
            $scope.$apply();
        });
    }

    $scope.getNow = function () {
        return new Date();
    };

    //在这里处理要进行的操作
    $scope.ok = function () {
        $window.print();
        $uibModalInstance.close();
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
}]);
